package xyz.riceball.springcloudstreambinderfile.file;

import org.springframework.cloud.stream.provisioning.ProducerDestination;
import org.springframework.integration.handler.AbstractMessageHandler;
import org.springframework.messaging.Message;
import xyz.riceball.springcloudstreambinderfile.property.FileExtendedBindingProperties;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * <p>
 * FileMessageHandler
 * </p>
 *
 * @author xiaovcloud
 * @since 2024/6/13 17:12
 */
public class FileMessageHandler extends AbstractMessageHandler {
	FileExtendedBindingProperties fileExtendedBindingProperties;
	ProducerDestination destination;

	public FileMessageHandler(ProducerDestination destination, FileExtendedBindingProperties fileExtendedBindingProperties) {
		this.destination = destination;
		this.fileExtendedBindingProperties = fileExtendedBindingProperties;
	}

	@Override
	protected void handleMessageInternal(Message<?> message) {
		try {
			if (message.getPayload() instanceof byte[]) {
				Files.write(Paths.get(fileExtendedBindingProperties.getPath() + File.separator + destination.getName() + ".txt"), (byte[]) message.getPayload());
			} else {
				throw new RuntimeException("处理消息失败");
			}
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
}
